package com.bby.disk.controller;

import cn.hutool.core.util.ObjectUtil;
import com.bby.common.config.GlobalSettings;
import com.bby.common.exception.BBYException;
import com.bby.common.utils.R;
import com.bby.common.utils.StatusCode;
import com.bby.common.aop.ParseToken;
import com.bby.disk.bean.UploadStatus;
import com.bby.disk.bean.req.SimpleUploadData;
import com.bby.disk.bean.req.UploadTaskInfo;
import com.bby.disk.manager.upload.OfflineThreadManager;
import com.bby.disk.service.IUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * 网盘-文件上传
 */
@RestController
@RequestMapping("upload")
public class UploadController implements DisposableBean {
    /*
    *******Parameters******
    guid: 0.029445724279864027
    id: WU_FILE_0
    name: 3-实习成果简介.doc
    type: application/msword
    lastModifiedDate: Mon Sep 20 2021 15:50:02 GMT+0800 (中国标准时间)
    size: 17408
    chunks: 2
    chunk: 1
    *******part******
    file
    3-实习成果简介.doc
    2048
    *************
 */
    IUploadService uploadService;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    public UploadController(IUploadService uploadService) {
        this.uploadService = uploadService;
    }

    /**
     * 预上传
     * @param uploadTaskInfo 结果
     */
    @ParseToken
    @PostMapping("preUpload")
    public R preUpload(String userId,@RequestBody UploadTaskInfo uploadTaskInfo) throws BBYException {
        logger.debug("预上传，userId={},req={}",userId, uploadTaskInfo);
        logger.debug(GlobalSettings.TEMP_FILES_DIR);
        String path = uploadTaskInfo.getTarget();
        if (path.startsWith("/")){
            if (ObjectUtil.isEmpty(userId)){
                return R.error(StatusCode.NOT_LOGIN,"请登录！");
            }
            uploadTaskInfo.setTarget(userId+path);
        }
        uploadService.preUpload(userId, uploadTaskInfo);
        return R.ok(uploadTaskInfo);
    }

    /**
     * 取消上传
     * @param guid guid 上传任务id
     */
    @DeleteMapping("delUpload/{guid}")
    public R delUpload(@PathVariable String guid) {
        logger.debug("取消上传 guid={}",guid);
        logger.debug(GlobalSettings.TEMP_FILES_DIR);
        uploadService.delTask(guid);
        return R.ok();
    }
    /**
     * 获取上传状态
     * @param guid 上传任务id
     */
    @GetMapping("status/{guid}")
    public R uploadStatus(@PathVariable String guid) throws BBYException {
        logger.debug("查看状态，guid={}",guid);
        UploadStatus status = uploadService.getUploadStatus(guid);
        logger.debug("状态:status={}",status);
        return R.ok(status);
    }

    /**
     * 普通上传
     * @param inputStream 文件流
     * @param guid 上传id
     * @param offset 从多少字节开始上传
     */
    @ResponseBody
    @ParseToken
    @PostMapping("simple/{guid}")
    public R uploadSimple(String userId, InputStream inputStream,@PathVariable String guid, @RequestParam Long offset) throws BBYException {
        SimpleUploadData simpleUploadData  = new SimpleUploadData(guid,offset,new BufferedInputStream(inputStream));
        logger.debug("普通上传：{}",simpleUploadData);
        uploadService.simpleUploadFile(userId,guid,simpleUploadData);
        return R.ok();
    }

    /**
     * 设置头像，必须登录
     * @param userId 必须在headers中带token（必须登录）
     * @param avatar 头像文件
     */
    @ParseToken(require = true)
    @PostMapping("avatar")
    public R setAvatar(String userId, MultipartFile avatar) throws BBYException {
        uploadService.setAvatar(userId,avatar);
        return R.ok();
    }

//    /**
//     * 分片上传
//     * @param uploadData 上传数据
//     * @return
//     */
//    @ResponseBody
//    @PostMapping("trunk")
//    public R uploadPartTrunk(ChunkedUploadData uploadData){
//        String userId="16328330937754942";
//        System.out.println(uploadData);
//        ServiceResult result = null;
//        try {
//            result = uploadService.uploadPartTrunk(userId, uploadData);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return R.ok(result);
//    }


    @Override
    public void destroy() throws Exception {
        OfflineThreadManager.shutdown();
    }
}
